package com.lemon.secondhandplatform.util;

import java.util.HashMap;
import java.util.Map;

/**
 * 图片工具类
 */
public class PhotoUtils {

    /**
     * 获取合适的单位
     *
     * @param size 文件大小
     * @return
     */
    public static String getUnit(double size) {
        int i;
        for (i = 0; i < 3; i++) {
            if (size / 1024 < 1) {
                break;
            }
            size = size / 1024;
        }

        switch (i) {
            case 0:
                return "byte";

            case 1:
                return "KB";

            case 2:
                return "MB";

            case 3:
                return "G";

            default:
                return "byte";
        }

    }

    /**
     * 将图片大小转化为合适的单位和大小
     *
     * @param size
     * @return
     */
    public static Map convert(double size) {
        Map<String, Object> map = new HashMap<>();

        int i;
        for (i = 0; i < 3; i++) {
            if (size / 1024 < 1) {
                break;
            }
            size = size / 1024;
        }

        //精确到小数点后两位
        size = Double.parseDouble(String.format("%.2f", size));
        map.put("size", new Double(size));

        switch (i) {
            case 0:
                map.put("unit", "byte");
                break;

            case 1:
                map.put("unit", "KB");
                break;

            case 2:
                map.put("unit", "MB");
                break;

            case 3:
                map.put("unit", "G");
                break;

            default:
                map.put("unit", "byte");
                break;
        }

        return map;
    }
}
